<?php

namespace Lib;

final class Jpush {
    use \Lib\Traits\Instance;

    public function __construct($app_key = null, $master_secret = null, $url = null) {
        $this->app_key       = \Yaf\Registry::get('config')->get('resource.jpush.appkey');
        $this->master_secret = \Yaf\Registry::get('config')->get('resource.jpush.masterSecret');
        $this->url           = \Yaf\Registry::get('config')->get('resource.jpush.url');
    }

    /**
     * @desc 调用推送方法
     *
     * @param        $receive
     * @param        $content
     * @param string $m_type
     * @param string $m_txt
     * @param string $m_time
     */
    public function send_pub($receive, $content, $m_type = 'http', $m_txt = '', $m_time = '86400') {
        $result = $this->push($receive, $content, $m_type, $m_txt, $m_time);

        if($result) {
            $res_arr = json_decode($result, true);
            if(isset($res_arr['error'])) {
                // echo $res_arr['error']['message'];
                $error_code = $res_arr['error']['code'];

                switch($error_code) {
                    case 200:
                        $message = '发送成功！';
                        break;
                    case 1000:
                        $message = '失败(系统内部错误)';
                        break;
                    case 1001:
                        $message = '失败(只支持 HTTP Post 方法，不支持 Get 方法)';
                        break;
                    case 1002:
                        $message = '失败(缺少了必须的参数)';
                        break;
                    case 1003:
                        $message = '失败(参数值不合法)';
                        break;
                    case 1004:
                        $message = '失败(验证失败)';
                        break;
                    case 1005:
                        $message = '失败(消息体太大)';
                        break;
                    case 1008:
                        $message = '失败(appkey参数非法)';
                        break;
                    case 1011:
                        $message = 'cannot find user by this audience';
                        break;
                    case 1020:
                        $message = '失败(只支持 HTTPS 请求)';
                        break;
                    case 1030:
                        $message = '失败(内部服务超时)';
                        break;
                    default:
                        $message = '失败(返回其他状态，目前不清楚额，请联系开发人员！)';
                        break;
                }
            } else {
                return true;
            }
        } else {
            $message = '接口调用失败或无响应';
        }

        // echo "<script>alert('推送信息:{$message}')</script>";
        return $message;
    }

    public function push($receiver = 'all', $content = '', $m_type = '', $m_txt = '', $m_time = '86400') {
        $base64           = base64_encode("$this->app_key:$this->master_secret");
        $header           = array("Authorization:Basic $base64", "Content-Type:application/json");
        $data             = array();
        $data['platform'] = 'all';
        $data['audience'] = $receiver;

        $data['notification'] = array(
            "alert"   => $content,

            "android" => array(
                "alert"      => $content,
                "title"      => "",
                "builder_id" => 1,
                "extras"     => array("type" => $m_type, "txt" => $m_txt),
            ),

            "ios"     => array(
                "alert"  => $content,
                "badge"  => "1",
                "sound"  => "default",
                "extras" => array("type" => $m_type, "txt" => $m_txt),
            ),
        );

        $data['message'] = array(
            "msg_content" => $content,
            "extras"      => array("type" => $m_type, "txt" => $m_txt),
        );

        $data['options'] = array(
            "sendno"          => time(),
            "time_to_live"    => $m_time,
            "apns_production" => false,
        );
        $param           = json_encode($data);
        $res             = $this->push_curl($param, $header);

        if($res) {
            return $res;
        } else {
            return false;
        }
    }

    /**
     * @desc 推送的Curl方法
     *
     * @param string $param
     * @param string $header
     * @return bool|mixed
     */
    public function push_curl($param = "", $header = "") {
        if(empty($param)) {
            return false;
        }

        $postUrl  = $this->url;
        $curlPost = $param;
        $ch       = curl_init();
        curl_setopt($ch, CURLOPT_URL, $postUrl);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($ch);
        curl_close($ch);

        return $data;
    }

}

